package com.marcosnobrega.android.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Application;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.provider.Contacts.Intents.UI;
import android.provider.Settings.System;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

import com.marcosnobrega.android.bean.UsersListItem;
import com.marcosnobrega.android.threadservice.PresenceThread;

public class AndroidNetwork extends Activity {
	
	static final String SERVICE_URL = "http://marcosnobrega.com/androidnetwork.php";
	static final String ACTION_POST_MESSAGE = "postar_mensagem";
	static final String ACTION_LIST_USERS = "listar_usuarios";
	static final String ACTION_LIST_MESSAGES = "listar_mensagens";
	static final String ACTION_CHECK_LOGIN = "verificar_login";
	static final String ACTION_PING_STATUS = "ping_status";
	
	private Context contexto = this;
	
	static private UsersListItem user;
	private Handler mHandler = new Handler();
	private Runnable mRunnable = new Runnable() {		
		
		@Override
		public void run() {
			mDialog.dismiss();
			
			if(user.getAndroid_id().equalsIgnoreCase(user.getNickname())){
				Builder builder = new AlertDialog.Builder(AndroidNetwork.this);
				builder.setIcon(R.drawable.euandroid);
				builder.setTitle(R.string.enternickname);
				EditText nicknameField = new EditText(AndroidNetwork.this);
				nicknameField.setText(R.string.empty);
				nicknameField.setId(1853);
				builder.setView(nicknameField);
				builder.setPositiveButton(R.string.btnConfirmar, new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						user.setNickname(((EditText)mDialog.findViewById(1853)).getText().toString());
						new Thread(PresenceThread.getInstance(user.getAndroid_id(), user.getNickname())).start();
						Intent usersListIntent = new Intent(AndroidNetwork.this, UserList.class);
						AndroidNetwork.this.startActivity(usersListIntent);
					}
				});
				mDialog = builder.create();
				mDialog.show();
			} else {
				new Thread(PresenceThread.getInstance(user.getAndroid_id(), user.getNickname())).start();
				Intent usersListIntent = new Intent(AndroidNetwork.this, UserList.class);
				AndroidNetwork.this.startActivity(usersListIntent);
			}
		}
	};
	private Dialog mDialog;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	   	
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.app_home);
	    
	    if(this.checkConnection()){    
	        String android_id = System.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
	        user = new UsersListItem(android_id, android_id);
	        
	        this.mDialog = ProgressDialog.show(this, "Conectando", "Verificando identificação do dispositivo");
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					Looper.prepare();
					try {
						checkLogin();
						mHandler.post(mRunnable);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					Looper.loop();
				}
			}).start();
    	}else{
    		//Levar tudo isso para uma classe de teste.
    		AlertDialog alerta = new AlertDialog.Builder(this).create();
    		alerta.setTitle("Falha na conexão");
    		alerta.setMessage("É necessario uma conexão de rede!");
    		alerta.setButton("Ok", new DialogInterface.OnClickListener() {				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Process.killProcess(Process.myPid());
				}
			});
    		alerta.show();
    	}
    }
    
    private boolean checkLogin() throws Exception{
    	
    	HttpPost request = new HttpPost(SERVICE_URL+"?action="+ACTION_CHECK_LOGIN);
    	DefaultHttpClient client = new DefaultHttpClient();
    	List<NameValuePair> params = new ArrayList<NameValuePair>();
    	params.add(new BasicNameValuePair("userAndroidId", user.getAndroid_id()));
    	
    	request.setEntity(new UrlEncodedFormEntity(params));
    	HttpResponse response = client.execute(request);
    	HttpEntity entity = response.getEntity();
    	String responseText = EntityUtils.toString(entity);
    	if(!responseText.equalsIgnoreCase("0")){
    		String[] userData = responseText.split(":");
    		user.setNickname(userData[1]);
    	}
    	
    	return true;
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
			case R.id.menu_list_users:
				Intent usersListIntent = new Intent(this, UserList.class);
				this.startActivity(usersListIntent);
				break;
				
			case R.id.settings:
				break;
				
			case R.id.menu_home:
				break;
				
			case R.id.menu_change_nickname:
				Builder builder = new AlertDialog.Builder(this);
				builder.setIcon(R.drawable.euandroid);
				builder.setTitle(R.string.enternickname);
				EditText nicknameField = new EditText(this);
				nicknameField.setText(R.string.empty);
				nicknameField.setId(1853);
				builder.setView(nicknameField);
				builder.setPositiveButton(R.string.btnConfirmar, new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						user.setNickname(((EditText)mDialog.findViewById(1853)).getText().toString());
						new Thread(PresenceThread.getInstance(user.getAndroid_id(), user.getNickname())).start();
					}
				});
				mDialog = builder.create();
				mDialog.show();
				break;

			default:
				Toast.makeText(this, "Função não implementada ainda!", Toast.LENGTH_LONG).show();			
				break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater mInflater = getMenuInflater();
        mInflater.inflate(R.menu.main_menu, menu);
        menu.getItem(0).setVisible(false);
        return true;
	}
	
	private boolean checkConnection(){
		try{
			ConnectivityManager connect = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
			NetworkInfo status = connect.getActiveNetworkInfo();
			if(status.isConnectedOrConnecting()){
				return true;
			}
			return false;
		}catch(Exception e){
			return false;
		}		
	}

	public static String getServiceUrl() {
		return SERVICE_URL;
	}

	public static String getActionPostMessage() {
		return ACTION_POST_MESSAGE;
	}

	public static String getActionListUsers() {
		return ACTION_LIST_USERS;
	}

	public static String getActionListMessages() {
		return ACTION_LIST_MESSAGES;
	}

	public static String getActionCheckLogin() {
		return ACTION_CHECK_LOGIN;
	}

	public static String getActionPingStatus() {
		return ACTION_PING_STATUS;
	}
    
}